package com.example.app.service;

import com.example.app.entity.Medication;
import com.example.app.repository.MedicationRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MedicationService {

    private final MedicationRepository medicationRepository;

    public List<Medication> getMedicationsByUserId(Long userId) {
        return medicationRepository.findByUserId(userId);
    }

    public List<Medication> getMedicationsByUserIdAndDate(Long userId, LocalDate date) {
        return medicationRepository.findByUserIdAndDate(userId, date);
    }

    public Medication saveMedication(Medication Medication) {
        // 尝试查找已有记录
        Medication existing = medicationRepository.findByUserIdAndDateAndTime(
                Medication.getUserId(), Medication.getDate(), Medication.getTime());

        if (existing != null) {
            // 更新已有记录的其他字段
            existing.setContext(Medication.getContext());
            // 如有其他字段也一起更新
            return medicationRepository.save(existing);
        } else {
            // 没有重复，新增
            return medicationRepository.save(Medication);
        }
    }
    public void deleteByUserId(Long userId) {
        medicationRepository.deleteByUserId(userId);
    }

    public void deleteByUserIdAndDate(Long userId, LocalDate date) {
        medicationRepository.deleteByUserIdAndDate(userId, date);
    }

    public void deleteByUserIdAndDateAndTime(Long userId, LocalDate date, LocalTime time) {
        medicationRepository.deleteByUserIdAndDateAndTime(userId, date, time);
    }

}
